#include "widget.h"
#include "ui_widget.h"

#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //设置窗口标题
    this->setWindowTitle("客户端");

    //实例化QNetworkAccessManager对象
    manager = new QNetworkAccessManager(this);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    //1.获取到输入框中的URL
    QUrl url( ui->lineEdit->text());
    //2.构造一个HPPT请求对象
    QNetworkRequest request(url);
    //3.发送请求
    QNetworkReply* response = manager->get(request);
    //4.通过信号槽,处理响应
    connect(response,&QNetworkReply::finished,this,[=](){
        //1.判定响应接受是否出错
        if(response->error() == QNetworkReply::NoError){
            //响应已经正确获取到
            //读取数据并显示到ui界面
            QString html = response->readAll();
            ui->plainTextEdit->setPlainText(html);
        } else {
            //响应获取出错
            //把出错原因显示到ui界面
            ui->plainTextEdit->setPlainText(response->errorString());
        }
        //还需要对response进行释放
        response->deleteLater();
    });
}
